﻿using System;
using System.Web.UI;
using DevExpress.Web.ASPxUploadControl;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn;
    SqlDataReader readCheckAccessPrivilete; 
    int CompetionID;
    string ClassID;
    string CourseID;
    string UploadDirectory = "~/Student/UploadImages/";
    string pathRoot = "";    
    string pathView="";
    bool flag = false;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["Student"] == null)
                Response.Redirect("~/Student/HomePage.aspx");
            CompetionID = Convert.ToInt32(Request.QueryString["id"].ToString());
            ClassID = Request.QueryString["ClassID"].ToString();
            CourseID = Request.QueryString["CourseID"].ToString();                        
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Institte_of_Fine_ArtsConnectionString"].ConnectionString);
            conn.Open();
            if (check_access_privilete())
            {
                txtDate.Text = DateTime.Today.ToLongDateString();
                mulviewPosting.ActiveViewIndex = 0;
                checkExist();
            }
            else
            {
                lbStatus.Text = "You not access privilete";
                mulviewPosting.ActiveViewIndex = 1;
            }
            
        }
        catch (NullReferenceException)
        {            
            lbStatus.Text = "Please select competition!";
            mulviewPosting.ActiveViewIndex = 1;
        }
        catch (Exception ex)
        {
            lbStatus.Text = ex.Message;
            mulviewPosting.ActiveViewIndex = 1;
        }
        
    }

    private bool check_access_privilete()
    {
        if (conn.State == ConnectionState.Closed)
            conn.Open();
        SqlCommand commCheckAccessPrivilete = new SqlCommand("SELECT * FROM Admission_Details WHERE StudentID='" + Session["Student"] + "' AND  ClassID='" + ClassID + "' AND CourseID='"+ CourseID +"'", conn);
        readCheckAccessPrivilete = commCheckAccessPrivilete.ExecuteReader();
        if (readCheckAccessPrivilete.HasRows)        
            return true;               
        else
            return false;        
        
    }

    private void checkExist()
    {
        try
        {
            if (!readCheckAccessPrivilete.IsClosed)            
                readCheckAccessPrivilete.Close();
            
            if(conn.State== ConnectionState.Closed)
                conn.Open();
            string strComm = "SELECT * FROM Posting WHERE StudentID = '" + Session["Student"] + "' AND CompetitionID= '" + CompetionID + "'";
            SqlCommand commSelect = new SqlCommand(strComm, conn);
            SqlDataReader read = commSelect.ExecuteReader();
            if (read.HasRows)
            {
                lbStatus.Text = "You have already posting!";
                mulviewPosting.ActiveViewIndex = 1;
                flag = true;
            }            
            conn.Close();
        }
        catch (Exception ex)
        {
            lbStatus.Text = "Error: " + ex.Message;
            mulviewPosting.ActiveViewIndex = 1;
            flag = false;
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        
    }
    protected void uplImage_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
    {
        e.CallbackData = SavePostedFile(e.UploadedFile);        
    }

    string SavePostedFile(UploadedFile uploadedFile)
    {               
        if (!uploadedFile.IsValid)
            return string.Empty;
        pathRoot = "StudentID_" + Session["Student"] + "_Date_" + DateTime.Today.ToLongDateString() + ".jpg";
        pathView = "StudentID_" + Session["Student"] + "_Date_" + DateTime.Today.ToLongDateString() + "_View.jpg";        
        string fileName = Path.Combine(MapPath(UploadDirectory), pathView);
        string fileNameRoot = Path.Combine(MapPath(UploadDirectory), pathRoot);
        using (Image original = Image.FromStream(uploadedFile.FileContent))        
        using (Image thumbnail = Inscribe(original, 100))
        {
            SaveToJpeg(thumbnail, fileName);
            SaveToJpeg(original, fileNameRoot);            
        }
        return pathView;
    }

    public static Image Inscribe(Image image, int size)
    {
        return Inscribe(image, size, size);
    }

    public static Image Inscribe(Image image, int width, int height)
    {
        Bitmap result = new Bitmap(width, height);
        using (Graphics graphics = Graphics.FromImage(result))
        {
            double factor = 1.0 * width / image.Width;
            if (image.Height * factor < height)
                factor = 1.0 * height / image.Height;
            Size size = new Size((int)(width / factor), (int)(height / factor));
            Point sourceLocation = new Point((image.Width - size.Width) / 2, (image.Height - size.Height) / 2);

            SmoothGraphics(graphics);
            graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(sourceLocation, size), GraphicsUnit.Pixel);
        }
        return result;
    }

    static void SmoothGraphics(Graphics g)
    {
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    }

    public static void SaveToJpeg(Image image, Stream output)
    {
        image.Save(output, ImageFormat.Jpeg);
    }

    public static void SaveToJpeg(Image image, string fileName)
    {
        image.Save(fileName, ImageFormat.Jpeg);
    }
    

    protected void btPosting_Click(object sender, EventArgs e)
    {
        try
        {
            if (!flag)
            {
                if (!readCheckAccessPrivilete.IsClosed)
                    readCheckAccessPrivilete.Close();
                string fileName = "StudentID_" + Session["Student"] + "_Date_" + DateTime.Today.ToLongDateString() + ".jpg";
                string fileNameView = "StudentID_" + Session["Student"] + "_Date_" + DateTime.Today.ToLongDateString() + "_View.jpg";
                string checkUpload = @"UploadImages/" + fileName;
                FileStream fs = new FileStream(Server.MapPath(checkUpload), FileMode.Open, FileAccess.Read);                ;
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                string strCommPosting = "INSERT INTO Posting(Painting, Description, Uploaded_Date, Price, StudentID, CompetitionID) VALUES ('~/Student/UploadImages/" + fileName + "', '" + memoDescription.Text + "','" + DateTime.Today.ToString() + "', '" + txtPrice.Text + "', '" + Session["Student"] + "','" + CompetionID + "')";
                SqlCommand comm = new SqlCommand(strCommPosting, conn);
                comm.ExecuteNonQuery();
                lbStatus.Text = "Posting sucessly!";
                conn.Close();
                mulviewPosting.ActiveViewIndex = 1;
                File.Delete(Server.MapPath(@"UploadImages/" + fileNameView));
            }            
        }
        catch(FileNotFoundException)
        {
            lbError.Text = "Pealse upload painting!";             
        }
        catch (Exception ex)
        {
            lbStatus.Text = "Error: " + ex.Message;
            mulviewPosting.ActiveViewIndex = 1; 
        }      
        
    }
}